package su.msk.jet.team01.chatik.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Server {

	private static Logger logger = LoggerFactory.getLogger(Server.class);

	public static void start(final int port) {
		ServerSocket providerSocket = null;
		NetworkClient client;
		Socket socket;

		try {
			providerSocket = new ServerSocket(port);

			logger.info("Server started, waiting for clients on port " + port);
			while (true) {
				socket = providerSocket.accept();
				client = new NetworkClient(socket);
				logger.info("Client (" + client.getIP() + ") connected.");
				client.startHandlers();
			}
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		} finally {
			if (providerSocket != null) {
				try {
					providerSocket.close();
				} catch (Exception ex) {
					logger.error("Error closing socket.", ex);
				}
			}
		}
	}

	private Server() {

	}
}
